package com.twd.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;

@ChannelHandler.Sharable
public class ChannelInit extends ChannelInitializer<SocketChannel> {
    public static ChannelInit INSTANCE = new ChannelInit();

    @Override
    protected void initChannel(SocketChannel sc) throws Exception {
        ChannelPipeline pipeline = sc.pipeline();
        // HTTP请求编解码器
        pipeline.addFirst(new HttpServerCodec());
        // 文件分块传输
        pipeline.addFirst(new ChunkedWriteHandler());
        // HTTP聚合器
        pipeline.addLast(new HttpObjectAggregator(1024 * 1024 * 5));
//        .addLast(new StringEncoder())//添加字符串编码器
//                .addLast(new ByteArrayEncoder());//添加字节数组的编码器
        // 自定义的HTTP请求处理器
        pipeline.addLast(HttpRequestHandler.INSTANCE);
        // WebSocket服务端协议处理
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        // WebSocket帧处理器
        pipeline.addLast(new TextWebSocketFrameHandler());
        // WebSocket帧处理器
        pipeline.addLast(new TextWebSocketHandler());
    }
}
